"""
created@2019/11/03
"""

from log import logger
from flask_restful import Resource, reqparse
from models.silo import SiloWxApp
from utils.resp import Resp
from utils.query import get_wx_app_info


class WxAppListApi(Resource):

    def get(self):
        """获取微信公众号列表接口"""

        logger.info('\n 收到获取微信公众号列表请求')
        apps = SiloWxApp.query.all()
        data = []
        for app in apps:
            dicts = {
                "app_name": app.app_name,
                "wx_app_id": app.wx_app_id,
                'app_id': app.app_id,
                'description': app.description,
            }
            data.append(dicts)
        return Resp.ok(data=data)

    def post(self):
        """批量注册微信公众号到silo推送系统"""
        parser = reqparse.RequestParser()
        parser.add_argument('wx_apps', type=list, location='json', required=True)
        args = parser.parse_args()

        for arg in args['wx_apps']:
            wx_app = SiloWxApp.query.filter(SiloWxApp.wx_app_id==arg.get('wx_app_id')).first()
            """
            SELECT silo.silo_wx_apps.id AS silo_silo_wx_apps_id, silo.silo_wx_apps.created_at AS silo_silo_wx_apps_created_at, silo.silo_wx_apps.updated_at AS silo_silo_wx_apps_updated_at, silo.silo_wx_apps.wx_app_id AS silo_silo_wx_apps_wx_app_id, silo.silo_wx_apps.app_name AS silo_silo_wx_apps_app_name, silo.silo_wx_apps.description AS silo_silo_wx_apps_description, silo.silo_wx_apps.app_id AS silo_silo_wx_apps_app_id, silo.silo_wx_apps.origin_id AS silo_silo_wx_apps_origin_id, silo.silo_wx_apps.alias AS silo_silo_wx_apps_alias
            FROM silo.silo_wx_apps
            WHERE silo.silo_wx_apps.wx_app_id = 99
            LIMIT 1;
            """
            if wx_app:
                arg['is_success'] = True
                arg['state'] = 'already exists'
                continue
            info = get_wx_app_info(arg.get('wx_app_id'))
            if info:
                # 查询存在记录
                wx_app = SiloWxApp(
                    wx_app_id=info['wx_app_id'],
                    app_id=info['app_id'],
                    app_name=info['app_name'],
                    description=info['description'],
                    origin_id=info['origin_id'],
                    alias=arg.get('alias', ''),  
                )
                wx_app.save()
                arg['is_success'] = True
            else:
                arg['is_success'] = False
        
        return Resp.ok(data=args['wx_apps'])
